package io;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class TestBufferReader {
    public static String filePath = "C:\\Users\\Sekla\\Desktop\\java_learn\\practice\\src\\io\\demo.txt";
    public static final CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();

    // 一行行读取
    public static void main(String[] args) {
        // BufferReader不是线程安全的
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        executorService.execute(new Task());
        executorService.execute(new Task());
        executorService.execute(new Task());
        executorService.execute(new Task());
        executorService.execute(new Task());

        try {
            executorService.shutdown();
            while (!executorService.awaitTermination(10, TimeUnit.MINUTES)) {
                System.out.println("线程池没有关闭");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("-----------------------------");
        list.forEach(System.out::println);
    }

    public static class Task implements Runnable {
        //  创建一个字符缓冲输入流

        @Override
        public void run() {
            //  创建一个字符缓冲输入流
            try (BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath))) {
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    list.add(line);
                    System.out.println(line);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
